package org.streamerstudio.core;

import java.util.List;

import org.gstreamer.ElementFactory;
import org.gstreamer.Plugin;
import org.gstreamer.PluginFeature;
import org.gstreamer.Registry;
import org.streamerstudio.model.gstreamer.registry.GstElement;
import org.streamerstudio.model.gstreamer.registry.GstPlugin;
import org.streamerstudio.model.gstreamer.registry.GstRegistry;
import org.streamerstudio.model.gstreamer.registry.RegistryFactory;

public class ModelFactory {

	public static GstRegistry getRegistryRoot(){
		Registry gstRegistry = Registry.getDefault();
		GstRegistry registry = RegistryFactory.eINSTANCE.createGstRegistry();
		List<Plugin> list = gstRegistry.getPluginList();
		for (Plugin gstPlugin : list) {
			GstPlugin modelPlugin = RegistryFactory.eINSTANCE.createGstPlugin();
			registry.getPlugins().add(modelPlugin);
			updatePlugin(gstPlugin, modelPlugin);
			List<PluginFeature> featureList = gstRegistry.getPluginFeatureListByPlugin(gstPlugin.getName());
			for (PluginFeature pluginFeature : featureList) {
				GstElement modelElement = RegistryFactory.eINSTANCE.createGstElement();
				modelElement.setPlugin(modelPlugin);
				updateElement(pluginFeature, modelElement);
			}
		}
		return registry;
	}
	
	private static void updateElement(PluginFeature pluginFeature, GstElement modelElement) {
		modelElement.setName(pluginFeature.getName());
		boolean isElementFactory = pluginFeature instanceof ElementFactory;
		modelElement.setAuthor(isElementFactory? ((ElementFactory)pluginFeature).getAuthor(): "N/A");
		modelElement.setDescription(isElementFactory? ((ElementFactory)pluginFeature).getDescription(): "N/A");
		modelElement.setGlibClass(isElementFactory? ((ElementFactory)pluginFeature).getKlass(): "N/A");
		modelElement.setLongName(isElementFactory? ((ElementFactory)pluginFeature).getLongName(): "N/A");
		if (isElementFactory){
			modelElement.setFactory((ElementFactory)pluginFeature);
		}
	}
	
	private static void updatePlugin(Plugin gstPlugin, GstPlugin modelPlugin) {
		modelPlugin.setName(gstPlugin.getName());
		modelPlugin.setDescription(gstPlugin.getDescription());
		modelPlugin.setFilename(gstPlugin.getFilename());
		modelPlugin.setLicense(gstPlugin.getLicense());
		modelPlugin.setLoaded(gstPlugin.isLoaded());
		modelPlugin.setName(gstPlugin.getName());
		modelPlugin.setOrigin(gstPlugin.getOrigin());
		modelPlugin.setPackage(gstPlugin.getPackage());
		modelPlugin.setSource(gstPlugin.getSource());
		modelPlugin.setVersion(gstPlugin.getVersion());
	}
}
